package cn.bellychang.wangzheng.binarysearch;

/**
 * @author ChangLiang
 * @date 2021/2/3
 */
public class SqrtUtil {

    public static float sqrt(float num) {
        if (num <= 0) {
            throw new RuntimeException("num should be greater than 0");
        }

        float lower = 0;
        float upper = num;

        while (lower + 0.00001 <= upper) {
            float middle = (upper - lower) / 2 + lower;
            if (middle * middle > num) {
                upper = middle;
            } else if (middle * middle < num) {
                lower = middle;
            } else {
                return middle;
            }
        }
        return upper;
    }
}
